import { ref } from 'vue';

import { useGroupSwitchStore } from './group-switch';
import { useSiteStore } from './site';
import { useStoreSwitchStore } from './store-switch';

export interface PendingRequest {
  config: any;
  resolve: (value: any) => void;
  reject: (error: any) => void;
}

export const useThreeLevelManager = () => {
  const groupSwitchStore = useGroupSwitchStore();
  const storeSwitchStore = useStoreSwitchStore();
  const siteStore = useSiteStore();

  // 控制三级切换弹窗的显示
  const showThreeLevelSwitch = ref(false);

  // 控制弹窗的初始步骤
  const initialStep = ref<'group' | 'site' | 'store'>('group');

  // 待处理的请求队列
  const pendingRequests = ref<PendingRequest[]>([]);

  /**
   * 检查集团、门店、站点信息是否完整
   */
  function checkRequiredInfo(): {
    isComplete: boolean;
    missingInfo: string[];
    nextStep: 'group' | 'site' | 'store';
  } {
    const missingInfo: string[] = [];
    let nextStep: 'group' | 'site' | 'store' = 'group';

    // 检查集团信息
    const currentGroup = groupSwitchStore.getCurrentGroup();
    if (currentGroup) {
      // 检查门店信息
      const currentStore = storeSwitchStore.getCurrentStore();
      if (currentStore) {
        // 检查站点信息
        const currentSite = siteStore.getCurrentSiteInfo();
        if (currentSite) {
          // 所有信息都完整
        } else {
          missingInfo.push('站点');
          nextStep = 'site';
        }
      } else {
        missingInfo.push('门店');
        nextStep = 'store';
      }
    } else {
      missingInfo.push('集团');
      nextStep = 'group';
    }

    return {
      isComplete: missingInfo.length === 0,
      missingInfo,
      nextStep
    };
  }

  /**
   * 打开三级切换弹窗
   */
  function openThreeLevelSwitch(step: 'group' | 'site' | 'store' = 'group') {
    initialStep.value = step;
    showThreeLevelSwitch.value = true;
  }

  /**
   * 关闭三级切换弹窗
   */
  function closeThreeLevelSwitch() {
    showThreeLevelSwitch.value = false;
    initialStep.value = 'group';
  }

  /**
   * 添加待处理的请求
   */
  function addPendingRequest(request: PendingRequest) {
    pendingRequests.value.push(request);
  }

  /**
   * 处理所有待处理的请求
   */
  function processPendingRequests() {
    const requests = [...pendingRequests.value];
    pendingRequests.value = [];

    requests.forEach(({ config, resolve, reject }) => {
      try {
        // 重新发送请求
        resolve(config);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 清除所有待处理的请求
   */
  function clearPendingRequests() {
    pendingRequests.value.forEach(({ reject }) => {
      reject(new Error('用户取消了设置'));
    });
    pendingRequests.value = [];
  }

  return {
    showThreeLevelSwitch,
    initialStep,
    pendingRequests,
    checkRequiredInfo,
    openThreeLevelSwitch,
    closeThreeLevelSwitch,
    addPendingRequest,
    processPendingRequests,
    clearPendingRequests,
  };
};
